<!-- @format -->

<template>
  <div class="card-container">
    <div v-for="(item, index) in params">
      <select-speakers
        :title="getMapLabel('speakerType', role) + '环节'"
        :speakerFormat="speakerFormat"
        v-model="item.speakers"
        :placeholder="`请选择${getMapLabel('speakerType', role)}`"
      >
        <template #button>
          <div v-if="role != 1">
            <van-icon v-if="!index" name="plus" @click="clickAdd" />
            <van-icon v-else name="minus" @click="clickRemove(index)" />
          </div>
        </template>
      </select-speakers>

      <select-topics
        title="讲题"
        v-model="item.topic"
      ></select-topics>

      <select-time
        title="开始时间"
        v-model="item.startTime"
      ></select-time>

      <select-time
        title="结束时间"
        v-model="item.endTime"
      ></select-time>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, toRefs, watch, computed } from 'vue'
import { showConfirmDialog } from 'vant';
import useConstant from '@/hooks/useConstant'
import { useStore } from 'vuex'
 
const store = useStore();
const emits = defineEmits(['update'])
const props = defineProps({
  speakerItem: {
    type: Object,
    default: () => ({})
  },
  role: {
    type: String,
    default: ''
  }
})
const { getMapLabel } = useConstant();

const params = ref([])
const priceConfig = computed(() => {
  return store.state.tenant.config.speakerFeeConfig ? JSON.parse(store.state.tenant.config.speakerFeeConfig) : {}
})

function clickAdd () {
  const { speakerItem } = toRefs(props);
  params.value.push(JSON.parse(JSON.stringify(speakerItem.value)))
}

function clickRemove (index) {
  showConfirmDialog({
    title: '温馨提示',
    message: '删除后无法恢复，确定要删除吗？',
  }).then(() => {
    params.value.splice(index, 1)
  }).catch(() => {})
}
function setRolePrice (role) {
  const roleConfig = priceConfig.value.find(item => item.role == role)
  const defaultPrice = roleConfig.fee.find(item => item.isDefault)
  return {
    speakerAppearanceFeeAftertax: defaultPrice?.aftertax || 0,
    speakerAppearanceFeePretax: defaultPrice?.pretax || 0,
  }
}
function speakerFormat(list) {
  const { role } = toRefs(props);
  return list.map((item) => ({
    speakerId: item.id || item.speakerId,
    ...setRolePrice(role.value),
    speakerName: item.name || item.speakerName,
    speakerRole: role.value
  }))
}

watch(
  () => params.value,
  (newVal) => emits('update', newVal),
  { deep: true }
)
onMounted(() => {
  clickAdd();
})

defineExpose({
  params,
  setParams (list = []) {
    params.value = list
    emits('update', list)
  }
})
</script>
